package shared;

import client.ClientController;
import client.gui.ClientGUI_Lobby;
import java.net.ServerSocket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import packet.CommandRequest;
import server.Lobby;
import server.LobbyNode;
import server.Server;

/**
 *
 * @author Administrator
 */
public class Launcher
{

  public static void main(String[] args)
  {
    if (args.length == 0)
    {
      System.out.println("Launched client");
      launchClient();
    }
    else 
    {
      //Is server
      try
      {
        int port = Integer.parseInt(args[0]);
        System.out.println("Launched server listening on port " + port);
        launchServer(port);
      }
      catch (Exception e)
      {
        System.out.println("Launched server listening on port " + Consts.DEFAULT_PORT);
        launchServer();
      }
    }
  }

  public static void launchClient()
  {
    PriorityBlockingQueue<CommandRequest> inQ = new PriorityBlockingQueue<>
                                      (Consts.SERVER_QUEUE_SIZE, new CompObj());

    PriorityBlockingQueue<CommandRequest> outQ = new PriorityBlockingQueue<>
                                      (Consts.SERVER_QUEUE_SIZE, new CompObj());

    ClientController controller = new ClientController(outQ);
    ClientGUI_Lobby lobbyGui = new ClientGUI_Lobby(controller);

    controller.setDependencies(inQ, lobbyGui);
    lobbyGui.setVisible(true);

  }
  
  public static void launchServer()
  {
    launchServer(Consts.DEFAULT_PORT);
  }
  
  public static void launchServer(int port)
  {
    PriorityBlockingQueue<CommandRequest> srvQ = new PriorityBlockingQueue<>
                                      (Consts.SERVER_QUEUE_SIZE, new CompObj());

    ArrayList<LobbyNode> lobbyList = new ArrayList<>();

    try
    {
      Server srv = new Server();
      Lobby lobby = new Lobby(srvQ, srv, lobbyList);

      ServerSocket server = new ServerSocket(port);

      srv.setVisible(true);

      srv.postLogMsg("Allowing lobby members");

      lobby.startListener();

      while(true)
      {
        lobby.addPlayer(srv.acceptClientConnection(server, srvQ));
      }
    }
    catch (SocketException e)
    {
      System.out.println("Socket already taken, exiting.");
    }
    catch (Exception ex)
    {
      Logger.getLogger(Server.class.getName()).log(Level.SEVERE, "Server", ex);
    }
  }
}
